package com.wl.common.mybatis.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author: wanglin
 * @date: 2023-07-12 周三
 * @Version: 1.0
 * @Description:
 */
public class PageUtils {
    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        PageUtils.applicationContext = applicationContext;
    }

    public static <T> Page<T> transferPage(Pageable pageable) {
        if (Objects.isNull(pageable)) {
            return new Page(1, 10);
        }

        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();

        Page page = new Page(pageNumber + 1, pageSize);

        Sort sort = pageable.getSort();
        if (sort.isUnsorted()) {
            return page;
        }

        SqlSessionFactory sqlSessionFactory = applicationContext.getBean(SqlSessionFactory.class);
        Configuration configuration = sqlSessionFactory.getConfiguration();
        boolean underCamel = configuration.isMapUnderscoreToCamelCase();

        page.setOrders(pageable.getSort()
                .stream()
                .map(r -> new OrderItem(underCamel ? StringUtils.camelToUnderline(r.getProperty()) : r.getProperty(), r.isAscending()))
                .collect(Collectors.toList()));

        return page;
    }

    public static <T> void transferSort(QueryWrapper queryWrapper, Sort sort) {
        if (Objects.isNull(queryWrapper) || Objects.isNull(sort) || sort.isUnsorted()) {
            return;
        }

        SqlSessionFactory sqlSessionFactory = applicationContext.getBean(SqlSessionFactory.class);
        Configuration configuration = sqlSessionFactory.getConfiguration();
        boolean underCamel = configuration.isMapUnderscoreToCamelCase();

        for (Sort.Order order : sort) {
            if (order.isAscending()) {
                queryWrapper.orderByAsc(underCamel ? StringUtils.camelToUnderline(order.getProperty()) : order.getProperty());
            } else {
                queryWrapper.orderByDesc(underCamel ? StringUtils.camelToUnderline(order.getProperty()) : order.getProperty());
            }
        }
    }
}
